Abstract Class

Abstraction is a process in which we hide complex implementation details and show only functionality to the user. In scala, we can achieve abstraction by using abstract class and trait. A class which is declared with abstract keyword is known as abstract class.

  • It contains both abstract and non-abstract methods 
  • It cannot support multiple inheritances. 
  • A class can extend only one abstract class.
  • The abstract method of abstract class are those method which do not contain any implementation Or in other words, the method which does not contain body is known as an abstract method.
Syntax:

abstract class class_name
{
// code..
}

Scala Abstract Class Example
In this example, we have created a myauthor abstract class. It contains an abstract method. A class book extends it and provides implementation of its details method. A class that extends an abstract class must provide implementation of its all abstract methods. You can't create object of an abstract class.
abstract class myauthor{
def details()
}
class book extends myauthor {
def details()
{
println("Author name: Ankita Saini")
println("Topic name: Abstract class in Scala")
}
}

object demo {
def main(args: Array[String])
{
var obj = new book()
obj.details()
}
}

Scala Abstract Class Example: Having Constructor, Variables and Abstract Methods

abstract class Bike(a:Int){
var b:Int = 20
var c:Int = 25
def run()
def performance(){
println("Performance awesome")
}
}

class Hero(a:Int) extends Bike(a){
c = 30
def run(){
println("Running fine...")
println("a = "+a)
println("b = "+b)
println("c = "+c)
}
}

object demo{
def main(args: Array[String]){
var h = new Hero(10)
h.run()
h.performance()
}
}
Note:-  If we try to create objects of the abstract class, then the compiler will give an error as shown in the below program.
scala>  var h = new Bike()
<console>:12: error: class Bike is abstract; cannot be instantiated
        var h = new Bike()

No comments:

Post a Comment